package com.freak.kotlinfitnessserver.activity.fragment.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.freak.kotlinfitnessserver.room.FeaturesData
import com.freak.kotlinfitnessserver.room.dao.FeaturesDataDao
import com.freak.kotlinfitnessserver.util.LogUtil
import com.freak.kotlinfitnessserver.util.ToastUtil
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch

class FeaturesViewModel(private val featuresDataDao: FeaturesDataDao) : ViewModel() {
    companion object {
        const val TAG: String = "FeaturesViewModel"
    }

    fun insertFeaturesData(item: FeaturesData) {
        LogUtil.i(DeviceInfoViewModel.TAG, "insertFeaturesData")
        viewModelScope.launch {
            val isSuccess = featuresDataDao.insert(item)
            if (isSuccess > 0) {
                ToastUtil.toastShort("插入成功")
            } else {
                ToastUtil.toastShort("插入失败")
            }
        }
    }

    fun updateFeaturesData(item: FeaturesData) {
        LogUtil.i(DeviceInfoViewModel.TAG, "updateFeaturesData")
        viewModelScope.launch {
            val isSuccess = featuresDataDao.update(item)
            if (isSuccess > 0) {
                ToastUtil.toastShort("更新成功")
            } else {
                ToastUtil.toastShort("更新失败")
            }
        }
    }

    fun getFeaturesDataList() {
        val resultList = mutableListOf<FeaturesData>()
        viewModelScope.launch {
            val flow: Flow<List<FeaturesData>> = featuresDataDao.getFeaturesDataList()
            flow.collect { list ->
                resultList.addAll(list)
            }
        }
    }

    suspend fun getFeaturesData(deviceType: String): FeaturesData? {
        var featuresData: FeaturesData? = null
        val job = viewModelScope.launch {
            featuresData = featuresDataDao.getFeaturesData(deviceType)
        }
        job.join()
        return featuresData
    }

    class FeaturesViewModelFactory(private val featuresDataDao: FeaturesDataDao) :
        ViewModelProvider.Factory {
        override fun <T : ViewModel> create(modelClass: Class<T>): T {
            if (modelClass.isAssignableFrom(FeaturesViewModel::class.java)) {
                @Suppress("UNCHECKED_CAST")
                return FeaturesViewModel(featuresDataDao) as T
            }
            throw IllegalArgumentException("Unknown ViewModel class")
        }
    }
}